<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人工智能检索</title>
    <script src="/assets/tailwind.js"></script>
    <link href="/assets/fontawesome-free-6.7.2-web/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#4080FF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        dark: '#1D2129',
                        light: '#F2F3F5',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .bg-gradient-blue {
                background: linear-gradient(135deg, #165DFF 0%, #4080FF 100%);
            }

            .shadow-card {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }

            .transition-all-300 {
                transition: all 0.3s ease;
            }

            .tab-active {
                @apply border-primary text-primary;
            }

            .table-row-hover {
                @apply hover:bg-gray-50 transition-all-300;
            }
        }
    </style>
</head>

<body class="bg-gray-50 font-inter text-dark min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-search text-primary text-xl"></i>
                <h1 class="text-xl font-bold text-primary">人工智能检索</h1>
            </div>
            <nav class="hidden md:flex items-center space-x-6">
                <a href="." class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-tachometer mr-2"></i> 仪表盘
                </a>
                <a href="file-browser" class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-folder-open mr-2"></i> 根目录设置
                </a>
                <a href="ai-search.html" class="text-primary font-medium flex items-center">
                    <i class="fa fa-search mr-2"></i> 人工智能检索
                </a>
                <a href="showlovewall.html" class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-heartbeat mr-2"></i> 表白墙
                </a>
                <a href="user-pwd-settings" class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-user-circle mr-2"></i> 管理员设置
                </a>
            </nav>
            <div class="flex items-center space-x-4">
                <a href="logs" class="text-gray-600 hover:text-primary transition-all duration-300 inline-block">
                    <i class="fa fa-bell text-xl"></i>
                </a>
                <div class="relative">
                    <button class="flex items-center space-x-2 focus:outline-none" id="adminDropdownBtn">
                        <img src="https://picsum.photos/200/200?random=1" alt="管理员头像"
                            class="w-8 h-8 rounded-full object-cover border-2 border-primary">
                        <span class="hidden md:inline-block font-medium">admin</span>
                        <i class="fa fa-angle-down text-gray-500"></i>
                    </button>
                    <!-- 下拉菜单（使用 Tailwind 类控制样式和交互） -->
                    <ul id="adminDropdownMenu" class="absolute right-0 mt-2 w-48 bg-white shadow-lg rounded-lg py-1 hidden">
                        <li>
                        <a href="user-pwd-settings" 
                            class="block px-4 py-2 text-sm text-gray-700 hover:bg-primary hover:text-white transition-colors">
                            <i class="fa fa-key mr-2"></i> 修改密码
                        </a>
                        </li>
                        <li>
                        <a href="logout" 
                            class="block px-4 py-2 text-sm text-gray-700 hover:bg-primary hover:text-white transition-colors">
                            <i class="fa fa-sign-out-alt mr-2"></i> 登出
                        </a>
                        </li>
                    </ul>
                </div>
                <button class="md:hidden text-gray-600 hover:text-primary transition-all-300">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主要内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <div class="max-w-5xl mx-auto">
            <!-- 页面标题 -->
            <div class="mb-8">
                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-2">人工智能检索</h2>
                <p class="text-gray-500">通过对话来检索文件和目录</p>
            </div>

            <!-- 对话区域 -->
            <div class="bg-white rounded-xl shadow-card p-6 mb-8 h-96 overflow-y-auto" id="chat-container">
                <!-- 对话消息将动态添加到这里 -->
            </div>

            <!-- 输入区域 -->
            <div class="flex space-x-4">
                <input type="text" id="search-input" placeholder="输入你的查询..."
                    class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300 w-full">
                <button id="search-btn"
                    class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all-300 flex items-center shadow-sm hover:shadow">
                    <i class="fa fa-search mr-2"></i> 搜索
                </button>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-6">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-gray-500 text-sm">&copy; 2025 北京椰子树信息技术有限公司. 保留所有权利.</p>
                </div>
                <div class="flex space-x-6">
                    <a href="http://www.coconet.cn" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-question-circle mr-1"></i> 帮助中心
                    </a>
                    <a href="http://www.coconet.cn" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-file-text-o mr-1"></i> 隐私政策
                    </a>
                    <a href="mailto:goodput3@qq.com" class="text-gray-500 hover:text-primary transition-all-300">
                        <i class="fa fa-phone mr-1"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        const chatContainer = document.getElementById('chat-container');
        const searchInput = document.getElementById('search-input');
        const searchBtn = document.getElementById('search-btn');

        // 模拟后端 API 调用
        // Send POST request to /lolcate endpoint with search query
        function searchFiles(query) {
            return fetch('/lolcate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ query }),
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .catch(error => {
                console.error('Search failed:', error);
                // Return empty results or handle error appropriately
                return [];
            });
        }


        // 添加用户消息到对话区域
        function addUserMessage(message) {
            const userMessage = document.createElement('div');
            userMessage.classList.add('bg-gray-200', 'p-3', 'rounded-lg', 'mb-2', 'self-end');
            userMessage.textContent = message;
            chatContainer.appendChild(userMessage);
        }

        // 添加系统消息到对话区域
        function addSystemWarnMessage(message) {
            const systemMessage = document.createElement('div');
            systemMessage.classList.add('bg-blue-100', 'p-3', 'rounded-lg', 'mb-2', 'self-start');
            systemMessage.innerHTML = '<p class="text-gray-600">未找到相关文件或目录。</p>';
            chatContainer.appendChild(systemMessage);
        }        
        // 添加系统消息到对话区域
        function addSystemMessage(message) {
            const systemMessage = document.createElement('div');
            systemMessage.classList.add('bg-blue-100', 'p-3', 'rounded-lg', 'mb-2', 'self-start');
            systemMessage.innerHTML = createBeautifulSearchResults(message);
            chatContainer.appendChild(systemMessage);
        }

        // 创建美化后的搜索结果HTML
        function createBeautifulSearchResults(message) {
            // 提取搜索结果部分（去除"搜索结果："前缀）
            const resultsText = message.substring(5);
            const resultsArray = resultsText.split('\n').filter(line => line.trim() !== '');
            
            if (resultsArray.length === 0) {
                return '<p class="text-gray-600">未找到相关文件或目录。</p>';
            }
            
            // 创建结果容器
            let html = `
                <div class="space-y-3 mt-2">
                    ${resultsArray.map(resultLine => {
                        // 解析结果行（格式："文件：文件名（路径：文件路径）"）
                        const isDirectory = resultLine.startsWith('目录');
                        const nameStart = isDirectory ? 3 : 3;
                        const nameEnd = resultLine.indexOf('（路径：');
                        const pathStart = nameEnd + 4;
                        const pathEnd = resultLine.lastIndexOf('）');
                        
                        const name = resultLine.substring(nameStart, nameEnd);
                        const path = resultLine.substring(pathStart, pathEnd);
                        
                        // 为目录和文件选择不同的图标
                        const iconClass = isDirectory 
                            ? 'fa-folder text-blue-500' 
                            : 'fa-file text-gray-500';
                        
                        
                        return `
                            <div class="bg-white rounded-lg shadow-sm p-3 hover:shadow transition-shadow duration-200">
                                <div class="flex items-start">
                                    <div class="flex-1 min-w-0">
                                        <h4 class="font-medium text-gray-900 truncate">${name}</h4>
                                        <p class="text-sm text-gray-500 mt-1 truncate">${path}</p>
                                    </div>
                                    <div class="ml-2 flex-shrink-0">
                                        <button class="text-gray-400 hover:text-gray-600 transition-colors" onclick="downloadPath('${path}')">
                                            <i class="fa fa-download"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            `;
            
            return html;
        }

        // 下载文件
        function downloadPath(path) {
            // 编码路径以确保URL安全
            const encodedPath = encodeURIComponent(path);
            const downloadUrl = `/download/${encodedPath}`;
            
            // 创建并点击下载链接
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.setAttribute('download', '');
            
            // 为文件添加下载中状态
            const toast = createToast('正在准备下载...', 'bg-blue-500');
            document.body.appendChild(toast);
            
            // 尝试下载
            try {
                link.click();
                
                // 模拟下载成功（实际应用中应根据服务器响应调整）
                setTimeout(() => {
                    updateToast(toast, '下载已开始', 'bg-green-500');
                    removeToastAfterDelay(toast);
                }, 1000);
            } catch (error) {
                console.error('下载失败:', error);
                updateToast(toast, '下载失败，请重试', 'bg-red-500');
                removeToastAfterDelay(toast);
            }
        }

        // 创建提示消息
        function createToast(message, bgColor) {
            const toast = document.createElement('div');
            toast.classList.add('fixed', 'bottom-4', 'right-4', bgColor, 'text-white', 'px-4', 'py-2', 'rounded', 'shadow-lg', 'z-50', 'flex', 'items-center');
            toast.innerHTML = `<i class="fa fa-spinner fa-spin mr-2"></i>${message}`;
            return toast;
        }

        // 更新提示消息内容和样式
        function updateToast(toast, message, bgColor) {
            toast.textContent = ''; // 清空内容
            toast.classList.remove('bg-blue-500', 'bg-green-500', 'bg-red-500');
            toast.classList.add(bgColor);
            
            // 根据状态添加不同图标
            const iconClass = bgColor === 'bg-green-500' 
                ? 'fa-check-circle' 
                : (bgColor === 'bg-red-500' ? 'fa-exclamation-circle' : 'fa-spinner fa-spin');
            
            toast.innerHTML = `<i class="fa ${iconClass} mr-2"></i>${message}`;
        }

        // 3秒后移除提示
        function removeToastAfterDelay(toast) {
            setTimeout(() => {
                toast.classList.add('opacity-0', 'transition-opacity', 'duration-300');
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 3000);
        }


        // 处理搜索请求
        async function handleSearch() {
            const query = searchInput.value.trim();
            if (query === '') return;

            addUserMessage(query);

            try {
                const results = await searchFiles(query);
                //console.log("result is ", results);
                if (results.length === 0) {
                    addSystemWarnMessage('未找到相关文件或目录。');
                } else {
                    let message = '搜索结果：\n';
                    results.forEach(result => {
                        message += `${result.type === 'directory' ? '目录' : '文件'}：${result.name}（路径：${result.path}）\n`;
                    });
                    //console.log("message is ", message);
                    addSystemMessage(message);
                }
            } catch (error) {
                addSystemWarnMessage('搜索过程中出现错误，请重试。');
            }

            searchInput.value = '';
        }

        // 绑定搜索按钮点击事件
        searchBtn.addEventListener('click', handleSearch);

        // 绑定输入框回车事件
        searchInput.addEventListener('keydown', (event) => {
            if (event.key === 'Enter') {
                handleSearch();
            }
        });
        const dropdownBtn = document.getElementById('adminDropdownBtn');
        const dropdownMenu = document.getElementById('adminDropdownMenu');
      
        // 切换菜单显示状态
        dropdownBtn.addEventListener('click', () => {
          dropdownMenu.classList.toggle('hidden');
          // 切换箭头旋转动画（可选）
          dropdownBtn.querySelector('.fa-angle-down').classList.toggle('rotate-180');
        });
      
        // 点击外部关闭菜单
        window.addEventListener('click', (event) => {
          if (!event.target.closest('#adminDropdownBtn, #adminDropdownMenu')) {
            dropdownMenu.classList.add('hidden');
            dropdownBtn.querySelector('.fa-angle-down').classList.remove('rotate-180');
          }
        });
    </script>
</body>

</html>
